package com.aiwu;

import android.content.Context;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;
import android.text.TextUtils;

import androidx.annotation.Nullable;

import com.aiwu.bean.ScreenConfig;
import com.aiwu.library.App;

import org.citra.citra_emu.utils.EmulationMenuSettings;

import java.util.Map;

public class PrefsHelper {
    private static final String TAG = PrefsHelper.class.getName();
    private SharedPreferences sharedPreferences;
    private SharedPreferences.Editor editor;
    private static final String GAME_ID = "game_id_";
    private static final String GAME_FILE_PATH = "game_file_path_";
    private static final String FONT = "font";
    public static final int FONT_INIT = 0;
    public static final int FONT_ACG = 1;
    @Deprecated
    private static final String FLOATING_LOCATION = "floating_location";
    private static final String FLOATING_BOTTOM_SCREEN_LOCATION = "floating_bottom_screen_location";
    private static final String FLOATING_SCREEN_LAYOUT_LOCATION = "floating_screen_layout_location";
    private static final String QUICK_SCREEN_LAYOUT = "quick_screen_layout";
    //region屏幕布局相关
    //横屏id
    public static final int SCREEN_CONFIG_ID_LANDSCAPE_START = 11;
    public static final int SCREEN_CONFIG_ID_LANDSCAPE_END = 20;
    //竖屏id
    public static final int SCREEN_CONFIG_ID_PORTRAIT_START = 100;
    public static final int SCREEN_CONFIG_ID_PORTRAIT_END = 110;
    private static final String SCREEN_CONFIG_PREFIX = "screen_config_";
    private static final String LAST_SCREEN_CONFIG = "last_screen_config";

    private static final String KEY_NAME = "name";
    private static final String KEY_TOP_LEFT = "topLeft";
    private static final String KEY_TOP_TOP = "topTop";
    private static final String KEY_TOP_RIGHT = "topRight";
    private static final String KEY_TOP_BOTTOM = "topBottom";
    private static final String KEY_BOTTOM_LEFT = "bottomLeft";
    private static final String KEY_BOTTOM_TOP = "bottomTop";
    private static final String KEY_BOTTOM_RIGHT = "bottomRight";
    private static final String KEY_BOTTOM_BOTTOM = "bottomBottom";
    //endregion
    private static final String LAST_VERSION_CODE = "last_version_code";

    public String getRomNameById(long gameId) {
        if (gameId == 0) {
            return "";
        }
        return getSharedPreferences().getString(GAME_ID + gameId, "");
    }

    public void setRomNameWithId(long gameId, String romName) {
        getEditor().putString(GAME_ID + gameId, romName).apply();
    }

    /**
     * 通过 初始游戏文件路径 查romName
     *
     * @param path 初始游戏文件路径
     * @return
     */
    public String getRomNameByPath(String path) {
        return getSharedPreferences().getString(GAME_FILE_PATH + path, "");
    }

    public void setRomNameWithPath(String path, String romName) {
        getEditor().putString(GAME_FILE_PATH + path, romName).apply();
    }

    public int getFont() {
        return getSharedPreferences().getInt(FONT, FONT_INIT);
    }

    public void setFont(int font) {
        getEditor().putInt(FONT, font).apply();
    }

    //region悬浮位置
    public void setFloatingBottomScreenLocation(int x, int y) {
        getEditor().putString(FLOATING_BOTTOM_SCREEN_LOCATION, x + "_" + y).apply();
    }

    @Nullable
    public int[] getFloatingBottomScreenLocation() {
        try {
            int[] location = new int[2];
            String str = getSharedPreferences().getString(FLOATING_BOTTOM_SCREEN_LOCATION, null);
            if (str == null) {
                str = getSharedPreferences().getString(FLOATING_LOCATION, null);
            }
            if (str == null) {
                return null;
            }
            String[] lc = str.split("_");
            location[0] = Integer.parseInt(lc[0]);
            location[1] = Integer.parseInt(lc[1]);
            return location;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public void removeFloatingBottomScreenLocation() {
        getEditor().remove(FLOATING_BOTTOM_SCREEN_LOCATION).apply();
        getEditor().remove(FLOATING_LOCATION).apply();
    }

    public void setFloatingScreenLayoutLocation(int x, int y) {
        getEditor().putString(FLOATING_SCREEN_LAYOUT_LOCATION, x + "_" + y).apply();
    }

    @Nullable
    public int[] getFloatingScreenLayoutLocation() {
        try {
            int[] location = new int[2];
            String str = getSharedPreferences().getString(FLOATING_SCREEN_LAYOUT_LOCATION, null);
            if (str == null) {
                return null;
            }
            String[] lc = str.split("_");
            location[0] = Integer.parseInt(lc[0]);
            location[1] = Integer.parseInt(lc[1]);
            return location;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 重置
     */
    public void resetFloatingScreenLayout() {
        getEditor().remove(FLOATING_SCREEN_LAYOUT_LOCATION)
                .remove(QUICK_SCREEN_LAYOUT)
                .apply();
    }
    //endregion

    //region 快捷切换屏幕布局
    public void setQuickScreenLayout(int layout1, int layout2) {
        getEditor().putString(QUICK_SCREEN_LAYOUT, layout1 + "_" + layout2).apply();
    }

    public boolean isQuickScreenLayout() {
        return getQuickScreenLayout() != null;
    }

    @Nullable
    public int[] getQuickScreenLayout() {
        try {
            int[] layout = new int[2];
            String str = getSharedPreferences().getString(QUICK_SCREEN_LAYOUT, null);
            if (str == null) {
                return null;
            }
            String[] l = str.split("_");
            layout[0] = Integer.parseInt(l[0]);
            layout[1] = Integer.parseInt(l[1]);
            return layout;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public void removeQuickScreenLayout() {
        getEditor().remove(QUICK_SCREEN_LAYOUT).apply();
    }
    //endregion

    //region屏幕布局相关

    /**
     * 获取上次的屏幕配置
     */
    public int getLastScreenConfigId() {
        return getSharedPreferences().getInt(LAST_SCREEN_CONFIG, EmulationMenuSettings.getLandscapeScreenLayout());
    }

    public void setLastScreenConfigId(int id) {
        getEditor().putInt(LAST_SCREEN_CONFIG, id).apply();
    }

    @Nullable
    public ScreenConfig getScreenConfig(int id) {
        SharedPreferences pref = App.getContext().getSharedPreferences(SCREEN_CONFIG_PREFIX + id, Context.MODE_PRIVATE);
        Map<String, String> map = (Map<String, String>) pref.getAll();
        if (map.isEmpty()) {
            return null;
        }
        ScreenConfig screenConfig = new ScreenConfig();
        screenConfig.setCustom(true);
        screenConfig.setId(id);
        screenConfig.setUsing(id == getLastScreenConfigId());
        String name = map.getOrDefault(KEY_NAME, "");
        screenConfig.setName(name);

        int topLeft = getOrDefault(map, KEY_TOP_LEFT);
        screenConfig.setTopLeft(topLeft);
        int topTop = getOrDefault(map, KEY_TOP_TOP);
        screenConfig.setTopTop(topTop);
        int topRight = getOrDefault(map, KEY_TOP_RIGHT);
        screenConfig.setTopRight(topRight);
        int topBottom = getOrDefault(map, KEY_TOP_BOTTOM);
        screenConfig.setTopBottom(topBottom);

        int bottomLeft = getOrDefault(map, KEY_BOTTOM_LEFT);
        screenConfig.setBottomLeft(bottomLeft);
        int bottomTop = getOrDefault(map, KEY_BOTTOM_TOP);
        screenConfig.setBottomTop(bottomTop);
        int bottomRight = getOrDefault(map, KEY_BOTTOM_RIGHT);
        screenConfig.setBottomRight(bottomRight);
        int bottomBottom = getOrDefault(map, KEY_BOTTOM_BOTTOM);
        screenConfig.setBottomBottom(bottomBottom);

        return screenConfig;
    }

    private static int getOrDefault(Map<String, String> map, String key) {
        String v = map.get(key);
        if (TextUtils.isEmpty(v)) {
            return 0;
        }
        return Integer.parseInt(v);
    }

    public void saveNewScreenConfig(int id, String name, int topLeft, int topTop, int topRight, int topBottom, int bottomLeft, int bottomTop, int bottomRight, int bottomBottom) {
        SharedPreferences pref = App.getContext().getSharedPreferences(SCREEN_CONFIG_PREFIX + id, Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = pref.edit();
        editor.clear();
        editor.putString(KEY_NAME, name);
        editor.putString(KEY_TOP_LEFT, topLeft + "");
        editor.putString(KEY_TOP_TOP, topTop + "");
        editor.putString(KEY_TOP_RIGHT, topRight + "");
        editor.putString(KEY_TOP_BOTTOM, topBottom + "");
        editor.putString(KEY_BOTTOM_LEFT, bottomLeft + "");
        editor.putString(KEY_BOTTOM_TOP, bottomTop + "");
        editor.putString(KEY_BOTTOM_RIGHT, bottomRight + "");
        editor.putString(KEY_BOTTOM_BOTTOM, bottomBottom + "");
        editor.apply();
    }

    public void editScreenConfigValue(int id, int topLeft, int topTop, int topRight, int topBottom, int bottomLeft, int bottomTop, int bottomRight, int bottomBottom) {
        SharedPreferences pref = App.getContext().getSharedPreferences(SCREEN_CONFIG_PREFIX + id, Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = pref.edit();
        editor.putString(KEY_TOP_LEFT, topLeft + "");
        editor.putString(KEY_TOP_TOP, topTop + "");
        editor.putString(KEY_TOP_RIGHT, topRight + "");
        editor.putString(KEY_TOP_BOTTOM, topBottom + "");
        editor.putString(KEY_BOTTOM_LEFT, bottomLeft + "");
        editor.putString(KEY_BOTTOM_TOP, bottomTop + "");
        editor.putString(KEY_BOTTOM_RIGHT, bottomRight + "");
        editor.putString(KEY_BOTTOM_BOTTOM, bottomBottom + "");
        editor.apply();
    }

    public void editScreenConfigName(int id, String newName) {
        SharedPreferences pref = App.getContext().getSharedPreferences(SCREEN_CONFIG_PREFIX + id, Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = pref.edit();
        editor.putString(KEY_NAME, newName);
        editor.apply();
    }

    public void removeScreenConfig(int id) {
        SharedPreferences pref = App.getContext().getSharedPreferences(SCREEN_CONFIG_PREFIX + id, Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = pref.edit();
        editor.clear()
                .apply();
    }
    //endregion

    //region 更新信息
    private void setLastVersionCode(int versionCode) {
        SharedPreferences.Editor editor = getEditor();
        editor.putInt(LAST_VERSION_CODE, versionCode);
        editor.apply();
    }

    public boolean isNewVersion(int currentVersionCode) {
        boolean isNewVersion = false;
        int lastVersionCode = getSharedPreferences().getInt(LAST_VERSION_CODE, 0);
        if (currentVersionCode > lastVersionCode) {
            isNewVersion = true;
        }
        setLastVersionCode(currentVersionCode);
        return isNewVersion;
    }

    //endregion
    private SharedPreferences getSharedPreferences() {
        if (sharedPreferences == null) {
            sharedPreferences = PreferenceManager.getDefaultSharedPreferences(App.getContext());
        }
        return sharedPreferences;
    }

    private SharedPreferences.Editor getEditor() {
        if (editor == null) {
            editor = getSharedPreferences().edit();
        }
        return editor;
    }

    private PrefsHelper() {
    }

    public static PrefsHelper getInstance() {
        return Holder.INSTANCE;
    }

    private static class Holder {
        private static PrefsHelper INSTANCE = new PrefsHelper();
    }
}
